package com.tusuo.stds.ui.similarity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.tusuo.stds.Constants;
import com.tusuo.stds.R;
import com.tusuo.stds.rest.LevelDetail;
import com.tusuo.stds.rest.Question;
import com.tusuo.stds.rest.RequestQuestionBean;
import com.tusuo.stds.rest.SimilarityDetail;
import com.tusuo.stds.rest.SimilarityInfo;
import com.tusuo.stds.ui.BaseToolbarActivity;
import com.tusuo.stds.ui.ToolbarOwner;
import com.tusuo.stds.ui.draft.DraftActivity_;
import com.tusuo.stds.ui.question.QuestionAdapterForSimilarity;
import com.tusuo.stds.util.CustomViewPager;
import com.tusuo.stds.util.webview.WebViewManager;

import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.StringRes;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import myandroid.library.util.ApplicationHelper;
import rx.functions.Action0;


@EActivity(R.layout.activity_question_webview)
public class SimilarityTempActivity extends BaseToolbarActivity<SimilarityTempView,SimilarityTempPresenter> implements SimilarityTempView {

    @ViewById(R.id.question_viewpager)
    CustomViewPager viewPager;

    @ViewById(R.id.question_tv_no_questions)
    TextView tvNoQuestions;
    @ViewById(R.id.question_tv_type)
    TextView tvType;
    @ViewById(R.id.question_tv_count)
    TextView tvCount;

    @StringRes(R.string.question_type_single)
    String strTypeSingle;
    @StringRes(R.string.question_type_multi)
    String strTypeMulti;
    @StringRes(R.string.question_type_tf)
    String strTypeTF;
    @StringRes(R.string.question_type_unsure)
    String strTypeUnsure;
    @StringRes(R.string.question_pre_download)
    String strPreDownload;

    @ColorRes(R.color.white)
    int colorWhite;
    @ColorRes(R.color.black)
    int colorBlack;

    public static final int QUESTION_TYPE_SINGLE = 1;
    public static final int QUESTION_TYPE_MULTI = 2;
    public static final int QUESTION_TYPE_TF = 3;
    public static final int QUESTION_TYPE_UNSURE = 7;

    private String mSecretKey;
    private SimilarityDetail mSimilarityDetail;
    private String mToolbarTitle;
    private int lastIndex;
    private ArrayList<WebViewManager> mWebViewManagerList = new ArrayList<>();
    private QuestionAdapterForSimilarity adapter3;
    private LevelDetail mLevelDetail;
    private final List<View> listView = new ArrayList<>();
    private ArrayList<String> answerContents = new ArrayList<>();

    private long lastTime;
    private long currentTime;

    private SimilarityInfo mSimilarityInfo;


    @NonNull
    @Override
    public SimilarityTempPresenter createPresenter() {
        return new SimilarityTempPresenter(this);
    }

    @Override
    public void setSecretKey(String secretKey) {
        mSecretKey = secretKey;
    }

    @Override
    public void setSimilarity(SimilarityDetail similarityDetail) {
        mSimilarityDetail = similarityDetail;
        initData();
    }

    @Override
    public void initFirst() {
    }

    @Override
    public void toNextQuestion() {
        handler.sendEmptyMessageDelayed(123,1000);
    }

    @Override
    public void requestSubmitQuestion(int questionId, long elapseSec, boolean isFinal, String answerContent) {
        RequestQuestionBean bean = new RequestQuestionBean();
        bean.questionId = questionId;
        bean.elapseSec = elapseSec;
        bean.answerContent = answerContent;
        bean.isFinal = isFinal;
        Message msg = new Message();
        msg.what = 321;
        msg.obj = bean;
        handler.sendMessageDelayed(msg,3000);
    }

    private boolean mIsTodayFinished = false;

    @Override
    public void setIsTodayFinished(long finishDate) {

    }

    @Override
    public void setSimilarityResult(SimilarityInfo similarityInfo) {
        mSimilarityInfo = similarityInfo;
    }

    void initData() {
        setupUI(this);

        tvNoQuestions.setVisibility(View.GONE);

        mToolbarTitle = mSimilarityDetail.Title;

        List<ToolbarOwner.MenuAction> menuActionList = new ArrayList<>();

        ToolbarOwner.MenuAction menuAction = new ToolbarOwner.MenuAction("草稿", new Action0() {
            @Override
            public void call() {
                startActivity(new Intent(SimilarityTempActivity.this, DraftActivity_.class));
            }
        }, 0);

        menuActionList.add(menuAction);

        ToolbarOwner.Config config = new ToolbarOwner.Config(mToolbarTitle, true, menuActionList);
        mToolbarOwner.setConfig(config);

        mLevelDetail = new LevelDetail();
        mLevelDetail.QuestionCount = mSimilarityDetail.QuestionCount;
        mLevelDetail.QuestionList = mSimilarityDetail.QuestionList;

        for (int i = 0; i < mSimilarityDetail.QuestionCount; i++) {
            View view = View.inflate(this, R.layout.item_question, null);
            BridgeWebView webView = (BridgeWebView) view.findViewById(R.id.item_question_webview);
            WebViewManager webViewManager = new WebViewManager(this, webView);

            Question question = mLevelDetail.QuestionList.get(i);
            question.Text = question.getDecodedText(mSecretKey);
            question.QuestionAnalysis = question.getDecodedQuestionAnalysis(mSecretKey);
            for (Question.QuestionOption option : question.QuestionOptionList) {
                option.Content = option.getDecodedContent(mSecretKey);
            }
            listView.add(view);
            mWebViewManagerList.add(webViewManager);
        }

        mIsTodayFinished = mSimilarityInfo.IsFinish;

        viewPager.setOffscreenPageLimit(2);

        if (mIsTodayFinished) {
            adapter3 = new QuestionAdapterForSimilarity(listView,mLevelDetail,mWebViewManagerList,mSecretKey,this, Constants.QUESTION_PAGE_TEMPLATE+ "?type=review",mSimilarityInfo.FinishCount);
            viewPager.enableRightSwipe(true);
            viewPager.enableLeftSwipe(true);
            viewPager.setAdapter(adapter3);
            viewPager.setCurrentItem(0);
            initText(mLevelDetail.QuestionList.get(0),0);
        }else {

            for (int i = 0; i < mSimilarityDetail.QuestionCount ; i ++) {
                Question question = mSimilarityDetail.QuestionList.get(i);
                if (!TextUtils.isEmpty(question.AnswerContent)) {
                    answerContents.add(question.AnswerContent);
                }
            }

            lastIndex = mSimilarityInfo.FinishCount;
            adapter3 = new QuestionAdapterForSimilarity(listView,mLevelDetail,mWebViewManagerList,mSecretKey,this, Constants.QUESTION_PAGE_TEMPLATE,mSimilarityInfo.FinishCount);
            viewPager.enableRightSwipe(false);
            viewPager.enableLeftSwipe(true);
            viewPager.setAdapter(adapter3);
            viewPager.setCurrentItem(mSimilarityInfo.FinishCount);
            initText(mLevelDetail.QuestionList.get(mSimilarityInfo.FinishCount > 0 ? mSimilarityInfo.FinishCount - 1 : 0),mSimilarityInfo.FinishCount > 0 ? mSimilarityInfo.FinishCount : 0);
        }


        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (state == CustomViewPager.SCROLL_STATE_IDLE) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            int curIndex = viewPager.getCurrentItem();

                            if (!mIsTodayFinished) {
                                if (curIndex != 0) {
                                    if (curIndex >= answerContents.size() || TextUtils.isEmpty(answerContents.get(curIndex))) {
                                        lastTime = System.currentTimeMillis();
                                    }
                                }

                                if (curIndex != lastIndex && lastIndex != -1) {
                                    viewPager.enableRightSwipe(true);
                                    viewPager.enableLeftSwipe(true);
                                } else {
                                    if (curIndex != 0) {
                                        viewPager.enableLeftSwipe(true);
                                        viewPager.enableRightSwipe(false);
                                    }
                                }
                            }

                            final Question curQuestion = mLevelDetail.QuestionList.get(curIndex);
                            initText(curQuestion,curIndex);
                        }
                    });

                }
            }
        });

        ApplicationHelper.getInstance().addActivity(this);

    }

    public void setLastTime() {
        if (viewPager.getCurrentItem() == mSimilarityInfo.FinishCount) {
            lastTime = System.currentTimeMillis();
        }
    }

    public void initText(Question question,int index) {
        switch (question.QuestionType) {
            case QUESTION_TYPE_SINGLE:
                tvType.setText(strTypeSingle);
                break;
            case QUESTION_TYPE_MULTI:
                tvType.setText(strTypeMulti);
                break;
            case QUESTION_TYPE_TF:
                tvType.setText(strTypeTF);
                break;
            case QUESTION_TYPE_UNSURE:
                tvType.setText(strTypeUnsure);
                break;
            default:
                tvType.setText("未知");
                break;
        }
        tvCount.setText(getString(R.string.question_count, index + 1, mLevelDetail.QuestionCount));
    }

    public BridgeHandler mSubmitAnswerHandler = new BridgeHandler() {
        @Override
        public void handler(String json, CallBackFunction function) {
            try {
                String answerContent = new JSONObject(json).getString("AnswerContent");
                answerContents.add(answerContent);
                currentTime = System.currentTimeMillis();
                long elapseSec = (currentTime - lastTime)/1000;
                boolean isFinal = false;
                if (viewPager.getCurrentItem() == mLevelDetail.QuestionCount - 1) {
                    isFinal = true;
                }
                if (!TextUtils.isEmpty(answerContent)) {
                    presenter.submitAnswer(answerContent,mLevelDetail.QuestionList.get(viewPager.getCurrentItem()).Id,elapseSec,isFinal);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 123) {
                int currentItem = viewPager.getCurrentItem();
                if (currentItem != mSimilarityDetail.QuestionCount - 1) {
                    viewPager.setCurrentItem(currentItem + 1);
                    adapter3.setAnswerContentReviewModeRepeat(currentItem);
                    lastIndex = currentItem + 1;
                    viewPager.enableLeftSwipe(true);
                    viewPager.enableRightSwipe(false);
                }else {
                    adapter3.setAnswerContentReviewModeRepeat(currentItem);
                }
            }else if (msg.what == 321) {
                RequestQuestionBean bean = (RequestQuestionBean) msg.obj;
                presenter.submitAnswer(bean.answerContent, bean.questionId, bean.elapseSec, bean.isFinal);
            }
        }
    };

}
